<?php
/**
* Author:rui
* Email:zer0131@vip.qq.com
* 付款
*/
class PayAction extends BaseAction{

    private $alipay_config = array();
    private $alipaydata = array();
	public function _initialize(){
		parent::_initialize();
		$filepath = APP_PATH.'Modules/Buy/Alipay';
		import('Corefunction', $filepath, '.php');
		import('Md5function', $filepath, '.php');
        import('Notify', $filepath, '.php');
        import('Submit', $filepath, '.php');

        //获取配置信息
        $this->alipay_config = C('alipay_config');
        //从数据库中获取卖家支付宝信息
        $alipayid = C('alipayid');
        $this->alipaydata = M('Buyconfig')->where(array('id'=>$alipayid))->find();
        $this->alipay_config['partner'] = $this->alipaydata['alipid'];
        $this->alipay_config['key'] = $this->alipaydata['alikey'];
  	}

    public function index(){
        $SEO = seo("", "", AppframeAction::$Cache['Config']['siteinfo'], AppframeAction::$Cache['Config']['sitekeywords']);
        
        $ordersn = $_GET['sn'];
        $data = M('Order')->where(array('ordersn'=>$ordersn))->find();
        if($data){
            $data['ispayname'] = getOrderStatus($data['ispay']);
        }

        $this->assign('data', $data);
        $this->assign("SEO", $SEO);
        $this->display();
    }

  	//支付
  	public function doPay(){
        //支付类型
        $payment_type = "1";
        //必填，不能修改

        //服务器异步通知页面路径
        $notify_url = C('alipay.notify_url');
        //需http://格式的完整路径，不能加?id=123这类自定义参数

        //页面跳转同步通知页面路径
        $return_url = C('alipay.return_url');
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

        //卖家支付宝帐户
        $seller_email = $this->alipaydata['aliaccount'];
        //必填

        //商户订单号
        $out_trade_no = trim($_POST['ordersn']);
        //商户网站订单系统中唯一订单号，必填

        //订单名称
        $subject = '商品-'.trim($_POST['title']).'-付款';
        //必填

        //付款金额
        $price = trim($_POST['price']);
        //必填

        //商品数量
        $quantity = "1";
        //必填，建议默认为1，不改变值，把一次交易看成是一次下订单而非购买一件商品

        //物流费用
        $logistics_fee = "0.00";
        //必填，即运费

        //物流类型
        $logistics_type = "EXPRESS";
        //必填，三个值可选：EXPRESS（快递）、POST（平邮）、EMS（EMS）
        
        //物流支付方式
        $logistics_payment = "SELLER_PAY";
        //必填，两个值可选：SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）
        
        //订单描述
        $body = "";
        
        //商品展示地址
        $show_url = "";
        //需以http://开头的完整路径，如：http://www.xxx.com/myorder.html

        //收货人姓名
        $receive_name = trim($_POST['truename']);
        //如：张三

        //收货人地址
        $receive_address = "";
        //如：XX省XXX市XXX区XXX路XXX小区XXX栋XXX单元XXX号

        //收货人邮编
        $receive_zip = "";
        //如：123456

        //收货人电话号码
        $receive_phone = "";
        //如：0571-88158090

        //收货人手机号码
        $receive_mobile = trim($_POST['phone']);
        //如：13312341234

        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service" => "create_partner_trade_by_buyer",
            "partner" => trim($this->alipay_config['partner']),
            "payment_type"  => $payment_type,
            "notify_url"    => $notify_url,
            "return_url"    => $return_url,
            "seller_email"  => $seller_email,
            "out_trade_no"  => $out_trade_no,
            "subject"   => $subject,
            "price" => $price,
            "quantity"  => $quantity,
            "logistics_fee" => $logistics_fee,
            "logistics_type"    => $logistics_type,
            "logistics_payment" => $logistics_payment,
            "body"  => $body,
            "show_url"  => $show_url,
            "receive_name"  => $receive_name,
            "receive_address"   => $receive_address,
            "receive_zip"   => $receive_zip,
            "receive_phone" => $receive_phone,
            "receive_mobile"    => $receive_mobile,
            "_input_charset"    => trim(strtolower($this->alipay_config['input_charset']))
        );

        //建立请求
        $alipaySubmit = new AlipaySubmit($this->alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        header('Content-Type:text/html;charset=utf-8');
        echo $html_text;
  	}

  	//同步通知
  	public function returnUrl(){
        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($this->alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result) {
            //验证成功
            //请在这里加上商户的业务逻辑程序代码
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表

            //商户订单号
            $out_trade_no = $_GET['out_trade_no'];

            //支付宝交易号
            $trade_no = $_GET['trade_no'];

            //交易状态
            $trade_status = $_GET['trade_status'];

            $data['alitradeno'] = $trade_no;

            if($_GET['trade_status'] == 'WAIT_BUYER_PAY') {
                
                $data['ispay'] = 1;
            }
            else if($_GET['trade_status'] == 'WAIT_SELLER_SEND_GOODS') {
                
                $data['ispay'] = 2; 
            }
            else if($_GET['trade_status'] == 'WAIT_BUYER_CONFIRM_GOODS') {
                
                $data['ispay'] = 3;
            }
            else if($_GET['trade_status'] == 'TRADE_FINISHED') {
                
                $data['ispay'] = 4;
            }
            else {
                //code
            }
            M('Order')->where(array('ordersn'=>$out_trade_no))->save($data);
            header('Content-Type:text/html;charset=utf-8');
            $this->redirect('Buy/Pay/index',array('sn'=>$out_trade_no),3,'正在处理数据...');
        }
        else {
            //验证失败
            header('Content-Type:text/html;charset=utf-8');
            $this->redirect('Buy/Index/index','',3,'支付失败，页面跳转至首页...');
        }
  	}

  	//异步通知
  	public function notifyUrl(){
        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($this->alipay_config);
        $verify_result = $alipayNotify->verifyNotify();

        if($verify_result) {
            //验证成功
            //请在这里加上商户的业务逻辑程序代
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号
            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];

            $data['alitradeno'] = $trade_no;

            if($_POST['trade_status'] == 'WAIT_BUYER_PAY') {
                
                $data['ispay'] = 1;
            }
            else if($_POST['trade_status'] == 'WAIT_SELLER_SEND_GOODS') {
                
                $data['ispay'] = 2;
            }
            else if($_POST['trade_status'] == 'WAIT_BUYER_CONFIRM_GOODS') {
                
                $data['ispay'] = 3;
            }
            else if($_POST['trade_status'] == 'TRADE_FINISHED') {
                
                $data['ispay'] = 4;               
            }
            else {
                //code
            }
            M('Order')->where(array('ordersn'=>$out_trade_no))->save($data);
            echo "success";
        }
        else {
            //验证失败
            echo "fail";
        }
  	}
}
?>